// src/features/reactions/api/use-toggle-reactions.ts
import {useCallback, useMemo, useState} from "react";
import {MARK_DATA_URL} from "@/lib/social/constants";
import {v4 as uuidv4} from 'uuid';

type Options = {
    onSuccess?: (workspaceId: string) => void
    onError?: (error: Error) => void
    onSettled?: () => void
    throwError?: boolean
}

type RequestType = {
    value: string
    messageId: string
    memberId: string
} | null


// client
export const useToggleReaction = () => {
    // create db message

    const [data, setData] = useState<RequestType>(null)
    const [error, setError] = useState<Error | null>(null)
    const [status, setStatus] =
        useState<"success" | "error" | "settled" | "pending" | null>()

    const isPending = useMemo(() => status === 'pending', [status])
    const isSuccess = useMemo(() => status === 'success', [status])
    const isSettled = useMemo(() => status === 'settled', [status])
    const isError = useMemo(() => status === 'error', [status])

    const mutate = useCallback(async (values: RequestType, options?: Options) => {
        console.log('toggle reaction', values?.value)

        try {
            setData(null)
            setError(null)
            setStatus('pending')

            // create workspace
            // const mRes = await fetch(`${MARK_DATA_URL}/messages/${values!.messageId}`)
            const mRes = await fetch(`/api/messages/${values!.messageId}`)
            const messages = await mRes.json()

            console.log('toggle relation old value', messages)

            let reactions: {
                count: number
                memberIds: string[]
                value: string
            }[]
            // if (messages.reactions)
            if (messages.relation)
                reactions = [...messages.relation]
                // reactions=reactions.map(r=>({
                //     ...r,
                //     memberIds: r.RelationMemberIds
                // }))
            else
                reactions = []

            if (reactions.length !== 0) {
                reactions = reactions.map(r => {
                    // 已有的value count+1
                    if (r.value === values!.value) {
                        if (!r.memberIds.includes(values!.memberId)) {
                            r.memberIds.push(values!.memberId)

                            return {
                                ...r,
                                count: r.count + 1,
                                memberIds: r.memberIds
                            }
                        } else {
                            // 如果已经有了继续点击, 就是取消
                            return {
                                ...r,
                                count: r.count - 1,
                                memberIds: r.memberIds.filter(m => m !== values!.memberId)
                            }
                        }
                    }

                    return r
                })
                // 新的value, 新增
                if (reactions.filter(r => r.value === values!.value).length === 0) {
                    reactions.push({
                        count: 1,
                        value: values!.value,
                        memberIds: [values!.memberId]
                    })
                }
                // 保留count不为0的
                reactions = reactions.filter(r => r.count !== 0)
            } else
                reactions.push({
                    count: 1,
                    value: values!.value,
                    memberIds: [values!.memberId]
                })

            const id = uuidv4()
            // const res = await fetch(`${MARK_DATA_URL}/messages/${values!.messageId}`, {
            const res = await fetch(`/api/messages/${values!.messageId}`, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    relations: reactions,
                    // createdAt: new Date().getTime(),
                    id
                }),
            })

            if (res.ok) {
                setStatus('success')
                options?.onSuccess?.(messages.id)
            }
            return messages.id
        } catch (error) {
            setStatus('error')
            options?.onError?.(error as Error)
            if (options?.throwError) throw error
        } finally {
            setStatus("settled")
            options?.onSettled?.()
        }
    }, []);

    return {
        mutate, error, isPending, isSuccess, isSettled, isError, data
    }
}